package com.redwood.report.widget.dialog;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.redwood.report.R;
import com.redwood.report.util.SpecialCalendar;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import antistatic.spinnerwheel.AbstractWheel;
import antistatic.spinnerwheel.OnWheelScrollListener;
import antistatic.spinnerwheel.adapters.AbstractWheelTextAdapter;

/**
 * Created by supeng on 2017/1/11 0011.
 */

public class PickTimePopWin extends PopupWindow {
    private View mMenuView;
    private Activity mContext;
    private SpecialCalendar mSpecialCalendar;
    private int bShowMode = 1;          //年月日小时分钟显示控制，  0：显示全部   1：只显示年月日    2：只显示小时分钟

    private OnSelectListener mListener;
    private TextView mCancelTv;
    private TextView mOkTv;
    private TextView mTitleTv;

    private AbstractWheel mHourWv = null;
    private AbstractWheel mMinWv = null;
    private HourWheelAdapter mHourWheelAdapter = null;
    private MinWheelAdapter mMinWheelAdapter = null;

    private AbstractWheel mYearWv = null;
    private AbstractWheel mMonthWv = null;
    private AbstractWheel mDayWv = null;
    private YearWheelAdapter mYearWheelAdapter = null;
    private MonthWheelAdapter mMonthWheelAdapter = null;
    private DayWheelAdapter mDayWheelAdapter = null;

    private final int YEAR_FORWARD = 10;        // 向前10年
    private final int YEAR_BACKWARD = 10;        // 向后10年

    private int mSelectHour = 0;
    private int mSelectMin = 0;

    private int mSelectYear;
    private int mSelectMonth;
    private int mSelectDay;
    

    public PickTimePopWin(Activity context, int mode) {
        super(context);
        mContext = context;
        bShowMode = mode;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.layout_pick_time, null);
        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.AnimBottom);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        
        initData();
        initView();
    }

    private void initData(){
        mSpecialCalendar = new SpecialCalendar();
        // 取当前时间作为默认选中
        Calendar calendar = Calendar.getInstance();
        mSelectYear = calendar.get(Calendar.YEAR);
        mSelectMonth = calendar.get(Calendar.MONTH) + 1;
        mSelectDay = calendar.get(Calendar.DAY_OF_MONTH);
        mSelectHour = calendar.get(Calendar.HOUR_OF_DAY);
        mSelectMin = calendar.get(Calendar.MINUTE);
    }
    
    private void initView(){
        mCancelTv = (TextView) mMenuView.findViewById(R.id.cancel_tv);
        mOkTv = (TextView) mMenuView.findViewById(R.id.ok_tv);
        mTitleTv = (TextView) mMenuView.findViewById(R.id.title_tv);
        mCancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PickTimePopWin.this.dismiss();
            }
        });
        mOkTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if( mListener != null ) {
                    mListener.onDateSelect(mSelectYear, mSelectMonth, mSelectDay, mSelectHour, mSelectMin);
                }
                PickTimePopWin.this.dismiss();
            }
        });

        //天选择滚轮
        mDayWheelAdapter = new DayWheelAdapter(mContext);
        mDayWv = (AbstractWheel) mMenuView.findViewById(R.id.day_wv);
        mDayWv.setVisibleItems(6);
        mDayWv.setViewAdapter(mDayWheelAdapter);
        mDayWv.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(AbstractWheel wheel) {
            }

            @Override
            public void onScrollingFinished(AbstractWheel wheel) {
                //计算当前选中是第几天
                mSelectDay = wheel.getCurrentItem() + 1;
            }
        });

        //年选择滚轮
        mYearWheelAdapter = new YearWheelAdapter(mContext);
        mYearWv = (AbstractWheel) mMenuView.findViewById(R.id.year_wv);
        mYearWv.setVisibleItems(6);
        mYearWv.setViewAdapter(mYearWheelAdapter);
        mYearWv.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(AbstractWheel wheel) {
            }

            @Override
            public void onScrollingFinished(AbstractWheel wheel) {
                //计算当前选中是第几年
                Calendar calendar = Calendar.getInstance();
                int startYear = calendar.get(Calendar.YEAR) - YEAR_FORWARD;
                mSelectYear = mYearWv.getCurrentItem() + startYear;
                //按照计算的年月判断是否需要刷新日滚轮组件
                int dayCount = mSpecialCalendar.getDaysOfMonth(mSpecialCalendar.isLeapYear(mSelectYear),mSelectMonth);
                //如果选中某年某月的天数不等于现在天数Adapter中的数量，则刷新
                if( dayCount != mDayWheelAdapter.getItemsCount()){
                    int selMon = mMonthWv.getCurrentItem();
                    Calendar calSel = Calendar.getInstance();
                    calSel.set(mSelectYear, selMon, 1);
                    mDayWheelAdapter.setDate(calSel);
                    //新的天数大于之前选中的最后一天时默认选中新的最后一天
                    if( dayCount < mDayWv.getCurrentItem() + 1) {
                        mSelectDay = dayCount;
                        mDayWv.setCurrentItem(dayCount-1);
                    }
                }
            }
        });

        //月选择滚轮
        mMonthWheelAdapter = new MonthWheelAdapter(mContext);
        mMonthWv = (AbstractWheel) mMenuView.findViewById(R.id.month_wv);
        mMonthWv.setVisibleItems(6);
        mMonthWv.setViewAdapter(mMonthWheelAdapter);
        mMonthWv.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(AbstractWheel wheel) {
            }

            @Override
            public void onScrollingFinished(AbstractWheel wheel) {
                //计算当前选中是第几月
                mSelectMonth = mMonthWv.getCurrentItem() + 1;
                //计算当前选中是第几年
                Calendar calSel = Calendar.getInstance();
                int startYear = calSel.get(Calendar.YEAR) - YEAR_FORWARD;
                int selYear = mYearWv.getCurrentItem() + startYear;
                //按照计算的年月判断是否需要刷新日滚轮组件
                int dayCount = mSpecialCalendar.getDaysOfMonth(mSpecialCalendar.isLeapYear(selYear),mSelectMonth);
                //如果选中某年某月的天数不等于现在天数Adapter中的数量，则刷新
                if( dayCount != mDayWheelAdapter.getItemsCount()){
                    int selMon = mMonthWv.getCurrentItem();
                    calSel.set(selYear, selMon, 1);
                    mDayWheelAdapter.setDate(calSel);
                    //新的天数大于之前选中的最后一天时默认选中新的最后一天
                    if( dayCount < mDayWv.getCurrentItem() + 1) {
                        mSelectDay = dayCount;
                        mDayWv.setCurrentItem(dayCount-1);
                    }
                }
            }
        });

        //小时选择滚轮
        mHourWheelAdapter = new HourWheelAdapter(mContext);
        mHourWv = (AbstractWheel) mMenuView.findViewById(R.id.hour_wv);
        mHourWv.setVisibleItems(6);
        mHourWv.setViewAdapter(mHourWheelAdapter);
        mHourWv.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(AbstractWheel wheel) {
            }

            @Override
            public void onScrollingFinished(AbstractWheel wheel) {
                mSelectHour = wheel.getCurrentItem();
            }
        });

        //分钟选择滚轮
        mMinWheelAdapter = new MinWheelAdapter(mContext);
        mMinWv = (AbstractWheel) mMenuView.findViewById(R.id.min_wv);
        mMinWv.setVisibleItems(6);
        mMinWv.setViewAdapter(mMinWheelAdapter);
        mMinWv.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(AbstractWheel wheel) {
            }

            @Override
            public void onScrollingFinished(AbstractWheel wheel) {
                mSelectMin = wheel.getCurrentItem();
            }
        });

        defaultUI();
    }

    /**
     * 刷新UI
     */
    private void defaultUI(){
        mHourWv.setCurrentItem(mSelectHour);
        mMinWv.setCurrentItem(mSelectMin);
        mYearWv.setCurrentItem(YEAR_FORWARD);
        mMonthWv.setCurrentItem(mSelectMonth-1);
        mDayWv.setCurrentItem(mSelectDay-1);

        if( bShowMode == 0 ){
            mYearWv.setVisibility(View.VISIBLE);
            mMonthWv.setVisibility(View.VISIBLE);
            mDayWv.setVisibility(View.VISIBLE);
            mHourWv.setVisibility(View.VISIBLE);
            mMinWv.setVisibility(View.VISIBLE);
        }else if( bShowMode == 1 ){
            mYearWv.setVisibility(View.VISIBLE);
            mMonthWv.setVisibility(View.VISIBLE);
            mDayWv.setVisibility(View.VISIBLE);
            mHourWv.setVisibility(View.GONE);
            mMinWv.setVisibility(View.GONE);
        }else if ( bShowMode == 2 ){
            mYearWv.setVisibility(View.GONE);
            mMonthWv.setVisibility(View.GONE);
            mDayWv.setVisibility(View.GONE);
            mHourWv.setVisibility(View.VISIBLE);
            mMinWv.setVisibility(View.VISIBLE);
        }
    }

    public void setOnSelectListener(OnSelectListener l) {
        mListener = l;
    }

    public interface OnSelectListener {
        public void onDateSelect(int year, int mon, int day, int hour, int min);
    }


    /**
     * 年滚轮适配器
     */
    private class YearWheelAdapter extends AbstractWheelTextAdapter {
        private List<String> years = new ArrayList<String>();

        public YearWheelAdapter(Context context) {
            super(context, R.layout.layout_year_wv, NO_RESOURCE);
            setItemTextResource(R.id.year_tv);
            Calendar calendar = Calendar.getInstance();
            int currYear = calendar.get(Calendar.YEAR);
            int startYear = currYear - YEAR_FORWARD;
            int endYear = currYear + YEAR_BACKWARD;
            for( int i = startYear; i <= endYear; i++ ){
                years.add( i + mContext.getString(R.string.time_year) );
            }
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        @Override
        public int getItemsCount() {
            return years.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return years.get(index);
        }
    }

    /**
     * 月滚轮适配器
     */
    private class MonthWheelAdapter extends AbstractWheelTextAdapter {
        private List<String> months = new ArrayList<String>();

        public MonthWheelAdapter(Context context) {
            super(context, R.layout.layout_month_wv, NO_RESOURCE);
            setItemTextResource(R.id.month_tv);
            for( int i = 1;i <= 12; i++ ){
                months.add( i + mContext.getString(R.string.time_month));
            }
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        @Override
        public int getItemsCount() {
            return months.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return months.get(index);
        }
    }

    /**
     * 日滚轮适配器
     */
    private class DayWheelAdapter extends AbstractWheelTextAdapter {
        private List<String> days = new ArrayList<String>();

        public DayWheelAdapter(Context context) {
            super(context, R.layout.layout_day_wv, NO_RESOURCE);
            setItemTextResource(R.id.day_tv);
            setDate(Calendar.getInstance());
        }

        public void setDate(Calendar selCalen){
            int yearSel = selCalen.get(Calendar.YEAR);
            int monthSel = selCalen.get(Calendar.MONTH)+1;
            int dayCount = mSpecialCalendar.getDaysOfMonth(mSpecialCalendar.isLeapYear(yearSel),monthSel);
            days.clear();
            for(int i = 1; i <= dayCount ; i++)
                days.add(i + mContext.getString(R.string.time_day));
            notifyDataChangedEvent();
            notifyDataInvalidatedEvent();
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        @Override
        public int getItemsCount() {
            return days.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return days.get(index);
        }
    }

    /**
     * 小时滚轮适配器
     */
    private class HourWheelAdapter extends AbstractWheelTextAdapter {
        private List<String> hours = new ArrayList<String>();

        public HourWheelAdapter(Context context) {
            super(context, R.layout.layout_hour_wv, NO_RESOURCE);
            setItemTextResource(R.id.hour_tv);
            for(int i = 0; i < 24; i++) {
                hours.add(String.format("%2d", i).replace(" ", "0") + mContext.getString(R.string.time_hour));
            }
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        @Override
        public int getItemsCount() {
            return hours.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return hours.get(index);
        }
    }

    /**
     * 分钟滚轮适配器
     */
    private class MinWheelAdapter extends AbstractWheelTextAdapter {
        private List<String> mins = new ArrayList<String>();

        public MinWheelAdapter(Context context) {
            super(context, R.layout.layout_min_wv, NO_RESOURCE);
            setItemTextResource(R.id.min_tv);
            for(int i = 0; i < 60; i++) {
                mins.add(String.format("%2d", i).replace(" ", "0")+ mContext.getString(R.string.time_min));
            }
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        @Override
        public int getItemsCount() {
            return mins.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return mins.get(index);
        }
    }
}
